import { legacy_createStore ,applyMiddleware  }from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { STORETYPE}from '../Type/Store.d';
import {ADDLISTTYPE,ALLADDTYPE,ADDCLEAR,NEWADD,EDITADD} from '../Type/AddType.d';

const initialState = {
    AddList : JSON.parse(window.localStorage.getItem('AddList') as any) || [],
}

const routes = (state:STORETYPE = initialState, { type, payload }:ALLADDTYPE) => {
    const Set_Item = (name:string,con:any)=>{
        window.localStorage.setItem(name,JSON.stringify(con));
    }

    switch (type) {

    case ADDLISTTYPE:
        state.AddList = payload;
        Set_Item('AddList',state.AddList);
        return { ...state}

    case ADDCLEAR:
        let addlistCopy = [...state.AddList];
        addlistCopy.forEach((item,index)=>{
            if(item.id == payload) addlistCopy.splice(index,1);
        })
        state.AddList = addlistCopy;
        Set_Item('AddList',state.AddList);
        return { ...state}

    case NEWADD:
        let newaddCopy = [...state.AddList];
        newaddCopy.unshift(payload);
        state.AddList = newaddCopy;
        Set_Item('AddList',state.AddList);
        return { ...state}

    case EDITADD:
        let editaddCopy = [...state.AddList];
        editaddCopy.forEach((item,index)=>{
            if(item.id == payload.id) Object.assign(item,payload)
        })
        state.AddList = editaddCopy;
        Set_Item('AddList',state.AddList);
        return { ...state}

    // case NEWADD:
    //     return { ...state}
    default:
        return { ...state}
    }
}

export default legacy_createStore(routes,applyMiddleware(logger,thunk))
